package com.wyix;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class WeatherApp {
    // 心知天气API接口（查询北京实时天气）
    private static final String API_URL = "https://api.seniverse.com/v3/weather/now.json?key=%s&location=linyi&language=zh-Hans&unit=c";

    public static void main(String[] args) {
        try {
            // 1. 读取配置文件中的API密钥
            String apiKey = loadApiKey();
            String requestUrl = String.format(API_URL, apiKey);

            // 2. 使用OkHttp发送GET请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(requestUrl).build();

            // 3. 执行请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("请求失败，状态码：" + response.code());
                }

                // 4. 解析JSON响应
                String responseBody = response.body().string();
                WeatherResponse weather = new Gson().fromJson(responseBody, WeatherResponse.class);

                // 5. 输出趣味天气信息（带控制台颜色）
                printWeatherInfo(weather);
            }
        } catch (Exception e) {
            System.err.println("❌ 出错啦：" + e.getMessage());
        }
    }

    // 从配置文件读取API密钥
    private static String loadApiKey() throws IOException {
        Properties prop = new Properties();
        try (InputStream input = WeatherApp.class.getClassLoader().getResourceAsStream("config.properties")) {
            prop.load(input);
            return prop.getProperty("api.key");
        }
    }

    // 趣味输出天气信息（控制台颜色）
    private static void printWeatherInfo(WeatherResponse weather) {
        WeatherData data = weather.results[0];
        String temp = data.now.temperature;
        String text = data.now.text;

        // 控制台颜色代码（绿色：正常，黄色：高温，蓝色：低温）
        String color = temp.compareTo("30") > 0 ? "\033[33m" :  // 黄色（>30℃）
                temp.compareTo("15") < 0 ? "\033[34m" :  // 蓝色（<15℃）
                        "\033[32m";  // 绿色（15-30℃）

        System.out.println("☀️ 实时天气报告：");
        System.out.println("城市：" + data.location.name);
        System.out.println(color + "温度：" + temp + "℃" + "\033[0m");  // 重置颜色
        System.out.println("天气：" + text);
        System.out.println("更新时间：" + data.last_update);
    }

    // 匹配API响应的Java对象（简化版）
    static class WeatherResponse {
        public WeatherData[] results;
    }

    static class WeatherData {
        public Location location;
        public Now now;
        public String last_update;
    }

    static class Location {
        public String name;
    }

    static class Now {
        public String text;
        public String temperature;
    }
}